# heading ----
message(paste0("Description: ", "function to create time variables"),
        "\n",
        paste0("Author: ", "Cedric Chambru (Department of Economics, University of Zurich)"),
        "\n",
        paste0("Last update: ", "07 June 2023"),
        "\n",
        paste0("List of functions: ", "time_var"))


# function: time_var ----
time_var <- function(df, year){
  year <- enquo(year)
  df %>%
    # century ----
    dplyr::mutate(
  		century = NA,
    	century = ifelse(!is.na(!! year), paste0(substr(!! year, 1, 2), "50"), NA),
    	century = as.numeric(century),
    	century = ifelse(substr(!! year, 3, 4) == "00", century - 100, century),
  		.before = !! year
  		) %>%
    # half century ----
    dplyr::mutate(
    	half_century = NA,
    	var_temp = as.numeric(substr(!! year, 3, 4)),
    	half_century = ifelse(var_temp >= 1 & var_temp <= 50, century - 25, half_century),
    	half_century = ifelse(var_temp >= 51 & var_temp <= 99, century + 25, half_century),
    	half_century = ifelse(var_temp == 0, century + 25, half_century),
    	.after = century
    	) %>%
    # quarter century ----
    dplyr::mutate(
    	quarter_century = NA,
    	var_temp = as.numeric(substr(!! year, 3, 4)),
    	quarter_century = ifelse(var_temp >= 1 & var_temp <= 25, century - 37.5, quarter_century),
    	quarter_century = ifelse(var_temp >= 26 & var_temp <= 50, century - 12.5, quarter_century),
    	quarter_century = ifelse(var_temp >= 51 & var_temp <= 75, century + 12.5, quarter_century),
    	quarter_century = ifelse(var_temp >= 76 & var_temp <= 99, century + 37.5, quarter_century),
    	quarter_century = ifelse(var_temp == 0, century + 37.5, quarter_century),
    	.after = half_century
    	) %>%
    dplyr::select(-var_temp) %>%
    # decade ----
    dplyr::mutate(
    	decade = NA,
    	decade = ifelse(!is.na(!! year), paste0(substr(!! year, 1, 3), "5"), NA),
    	decade = as.numeric(decade),
    	decade = ifelse(substr(!! year, 4, 4) == "0", decade - 10, decade),
    	.after = quarter_century
    	) %>%
    # half decade ----
    dplyr::mutate(
    	var_temp = as.numeric(substr(!! year, 4, 4)),
    	half_decade = NA,
    	half_decade = ifelse(var_temp >= 1 & var_temp <= 5, decade - 2.5, half_decade),
    	half_decade = ifelse(var_temp >= 6 & var_temp <= 9, decade + 2.5, half_decade),
    	half_decade = ifelse(var_temp == 0, decade + 2.5, half_decade),
    	half_decade = as.numeric(half_decade),
    	.after = decade
    	) %>%
  	dplyr::select(
  		-var_temp
  		)
}

